package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.MyEventDAO;
import model.UserDAO;
import beans.UserBean;
import beans.MyEventBean;




@WebServlet("/MyEventServlet")
public class MyEventServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MyEventServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try
		{	    
			UserBean user = new UserBean();
			ArrayList<MyEventBean> myevent = new ArrayList<MyEventBean>();
//			ArrayList<MessageBean> messages = new ArrayList<MessageBean>();
			
			//The parameters are gathered from the url, which is .../dropin/MessagesServlet?id=something&box=something&page=something
			//The parameters are saved into variables:
			user.setEmail(request.getParameter("id"));
			user = UserDAO.login(user);
			String pagenumberstring = request.getParameter("page");
			Integer pagenumber = new Integer(pagenumberstring);
			String box = request.getParameter("box");
			//Debug
			System.out.println(user.getName());
			System.out.println(pagenumberstring);
			System.out.println(box);
			
			//This is kinda tricky: since ALL messages are requested and saved in the ArrayList on the first call to the getReceived/SentMessages method,
			//the method should be called ONLY when the user request the first page of the inbox.
			//When he request other pages, the messages are fetched directly from the ArrayList that remains stored in memory
			
			if (pagenumber == 1) {
				if (box.equals("Hupcoming"))
					myevent = MyEventDAO.gethostupcoming(user);
				else if (box.equals("Hpast"))
					myevent = MyEventDAO.gethostpast(user);
				else if (box.equals("Gupcoming"))
					myevent = MyEventDAO.getguestupcoming(user);
				else if (box.equals("Gpast"))
					myevent = MyEventDAO.getguestpast(user);
			}
			
			
			
			int myeventCount = myevent.size();
			System.out.println(myeventCount);
			//Set the session's attributes
			HttpSession session = request.getSession(true);
			if (pagenumber == 1)
			session.setAttribute("displayevents", myevent);
			session.setAttribute("currentpagenumber", pagenumber);
			session.setAttribute("currentbox", box);
			session.setAttribute("myeventcount", myeventCount);
			response.sendRedirect("myevent.jsp"); //logged-in page      		
		} 


		catch (Throwable theException) 	    
		{
			System.out.println(theException); 
		}
	}
}
